﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;

namespace TestFTPPro
{
  public partial class Form1 : Form
  {
    private int iXH = 0;
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

      //
      iXH++;
      string sText = SHA256Encrypt(iXH.ToString());
      string sFile = string.Format(@"{0}/{1}/{2}.pdf",sText.Substring(0,1),sText.Substring(1,2),sText);
      using (FTPHelper ftp = new FTPHelper("192.168.19.135", "/", "fly2ky", "2042835"))
      {
        string[] PList = sFile.Split('/');
        for (int i = 0; i < PList.Length;i++ )
        {
          string sDir = PList[i];
          if (i != PList.Length - 1)  //目录
          {
            if (!ftp.IsDirectoryExist(sDir))
            {
              ftp.CreateDirectory(sDir);
            }

            ftp.GotoDirectory(sDir, false);

          }
          else  //文件
          {
            //ftp.Upload(@"D:\Test.pdf", sDir);
            using (FileStream fs = new FileStream(@"D:\Test.pdf", FileMode.Open))
            {
              string sBStr =SHA256Encrypt(fs);
              richTextBox1.AppendText(sBStr);
              richTextBox1.AppendText("\r\n");
              fs.Position = 0;  //很重要，从头上传，因为SHA256Encrypt(fs)，流的位置在末尾
              ftp.Upload(fs, sDir);

              //ftp.Download(@"D:\Test1.pdf", sDir);

              //using (FileStream ms = new FileStream(@"D:\Test1.pdf", FileMode.Open))
              using (MemoryStream ms = new MemoryStream())
              {
                ftp.Download(ms, sDir);
                ms.Position = 0;
                string sEStr = SHA256Encrypt(ms);
                richTextBox1.AppendText(sEStr);
                richTextBox1.AppendText("\r\n");

              }
              
            }          
           
          }

        }


      }


    }

      private string SHA256Encrypt(string text)
      {
        string pwd = "";
        SHA256 md5 = SHA256.Create();
        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(text));
        for (int i = 0; i < s.Length; i++)
        {
          pwd = pwd + s[i].ToString("X2");
        }
        return pwd;
      }

      private string SHA256Encrypt(Stream outputStream)
      {
        string pwd = "";
        SHA256 md5 = SHA256.Create();
        byte[] s = md5.ComputeHash(outputStream);
        for (int i = 0; i < s.Length; i++)
        {
          pwd = pwd + s[i].ToString("X2");
        }
        return pwd;
      }
    
  }
}
